package com.atguigu.flink.window;

import com.atguigu.flink.bean.WaterSensor;
import com.atguigu.flink.function.WaterSensorMapFunction;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * 单调递增，不考虑乱序
 */
public class WatermarkBoundedOut {
    public static void main(String[] args) throws Exception {
        // TODO 1.指定处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // TODO 2.设置并行度
        env.setParallelism(1);
        // TODO 3.指定网络端口获取数据
        DataStreamSource<String> socketDS = env.socketTextStream("hadoop102", 8888);
        // TODO 4.对数据进行类型转换
        SingleOutputStreamOperator<WaterSensor> mapDS = socketDS.map(new WaterSensorMapFunction());
        //
        SingleOutputStreamOperator<WaterSensor> withWaterMarkDS = mapDS.assignTimestampsAndWatermarks(WatermarkStrategy
                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                .withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
                    @Override
                    public long extractTimestamp(WaterSensor waterSensor, long recordTimestamp) {
                        return waterSensor.getTs();
                    }
                }));
        // TODO 5.按照传感器id进行分组
        KeyedStream<WaterSensor, String> keyByDS = withWaterMarkDS.keyBy(WaterSensor::getId);
        // TODO 6.对数据进行开窗 --> 滑动处理时间窗口
        WindowedStream<WaterSensor, String, TimeWindow> windowDS = keyByDS.window(TumblingEventTimeWindows.of(Time.milliseconds(10)));
        // TODO 7.对数据进行处理
        SingleOutputStreamOperator<String> processDS = windowDS.process(
                new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>() {
                    @Override
                    public void process(String s, ProcessWindowFunction<WaterSensor, String, String, TimeWindow>.Context context, Iterable<WaterSensor> iterable, Collector<String> collector) throws Exception {
                        String windowStart = DateFormatUtils.format(context.window().getStart(), "yyyy-MM-dd HH:mm:ss.SSS");
                        String windowEnd = DateFormatUtils.format(context.window().getEnd(), "yyyy-MM-dd HH:mm:ss.SSS");
                        long count = iterable.spliterator().estimateSize();
                        collector.collect("key = " + s + "的窗口[" + windowStart + "," + windowEnd + ")包含" + count + "条数据===>" + iterable.toString());
                    }
                }
        );
        // TODO 8.打印输出
        processDS.print();
        // TODO 9.提交作业
        env.execute();
    }
}
